import { categoryPost, categoryPut } from "@/api/course";
import { CategoryType } from "@/types/course";
import { Button, Form, Input, Select } from "antd";
import { useEffect } from "react";

const { Option } = Select;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
interface CateFormProps {
  handleUpdate: (arg: CategoryType) => void;
  data: Array<CategoryType>;
  edata: CategoryType | null;
}
const CategoryForm: React.FC<CateFormProps> = (props) => {
  const [form] = Form.useForm();

  const onFinish = (values: any) => {
    console.log(values);
    if (props.edata) {
      let { objectId } = props.edata;
      categoryPut(objectId, values).then(() => {
        props.handleUpdate({ ...values, objectId });
      });
    } else {
      categoryPost(values).then((res) => {
        props.handleUpdate({ ...values, objectId: res.data.objectId });
      });
    }
    onReset();
  };

  const onReset = () => {
    form.resetFields();
  };

  useEffect(() => {
    if (props.edata) {
      form.setFieldsValue(props.edata);
    } else {
      onReset();
    }
  }, [props.edata]);

  return (
    <Form
      {...layout}
      form={form}
      name="control-hooks"
      onFinish={onFinish}
      style={{ maxWidth: 600 }}
    >
      <Form.Item name="name" label="分类名称" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="parentId" label="父级类目" rules={[{ required: true }]}>
        <Select placeholder="请选择父级类目" allowClear>
          <Option value="0-0">顶级类目</Option>
          {props.data.map((item) => (
            <Option value={item.objectId}>{item.name}</Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
        <Button htmlType="button" onClick={onReset}>
          重置
        </Button>
      </Form.Item>
    </Form>
  );
};

export default CategoryForm;
